package org.fioma.tree.bytes;

import org.fioma.tree.Label;

public class LabelRefBytes implements Label<LabelRefBytes> {

	byte[] word;
	int pos, length;

	public LabelRefBytes(byte[] word, int pos, int length) {
		this(word);
		setPosLength(pos, length);
	}

	public LabelRefBytes(byte[] word) {
		this.word = word;
		this.pos = 0;
		this.length = word[0];
	}

	public byte[] getWord() {
		return word;
	}

	public int getPos() {
		return pos;
	}

	public void setPosLength(int pos, int length) {
		if (pos < 0 || pos + length > getLength()) {
			throw new RuntimeException("Pos " + pos + " and length " + length + " invalid in the word with length " + getLength());
		}
		this.pos = pos;
		this.length = length;
	}

	@Override
	public int getLength() {
		return length;
	}

	@Override
	public LabelRefBytes substring(int pos, int length) {
		if (pos < 0 || pos + length > getLength()) {
			throw new RuntimeException("Pos " + pos + " and length " + length + " invalid in the word with length " + getLength());
		}
		LabelRefBytes ret = new LabelRefBytes(getWord(), getPos() + pos, length);
		return ret;
	}

	@Override
	public LabelRefBytes substring(int pos) {
		return substring(pos, getLength() - pos);
	}

	@Override
	public char getChar(int pos) {
		return Tools.transformToChar(getByte(pos));
	}

	@Override
	public byte getByte(int pos) {
		return Tools.getByte(getWord(), pos);
	}

	@Override
	public int getMinsmatch(Label word) {
		int i;
		for (i = 0; i < getLength() && i < word.getLength(); i++) {
			if (getChar(i) != word.getChar(i)) {
				return i;
			}
		}
		if (getLength() == word.getLength()) {
			return -1;
		}
		return i;
	}

	public int getMinsmatch(LabelRefBytes word) {
		return Tools.getMismatch(getWord(), getPos(), getLength(), word.getWord(), word.getPos(), word.getLength());
	}

}
